<?php
namespace App\Config;

use PDO;
use PDOException;

// 数据库的连接等初始化配置
class Database{
    private $host = 'localhost';
    private $username = 'root';
    private $password = 'root';
    private $database = 'student_sysytem2';
    private $conn;
    private $charset = 'utf8mb4';

    /**
     * 获取数据库连接的对象
     * @return PDO
     */
    public function getConnection() {
        $this->conn = null;
        try {
            $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->database . ";charset=" . $this->charset;
            $this->conn = new PDO($dsn, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // echo "Connected successfully"; // 生产环境中应该删除这行
        } catch(PDOException $e) {
            // 在生产环境中记录日志而不是直接输出
            error_log("Database connection error: " . $e->getMessage());
        }
        
        return $this->conn; // 返回连接对象
    }
}

?>